from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from sensors.models import DevInfo
import time
import datetime
import logging

logger = logging.getLogger(__name__)
'''
def closeSensor(name):
    from sensors.models import SystemSitting
    manualStatus = SystemSitting.objects.get(type_name='manual').status
    if not manualStatus:
        import time
        targetDev = DevInfo.objects.get(dev_name=name)
        localtime = time.asctime(time.localtime(time.time()))
        """关闭传感器"""
        channel_layer = get_channel_layer()

        async_to_sync(channel_layer.group_send)("sensors", {
            "type": "events",
            "message": {
                'type': 'status',
                'msg': '已关闭'
            }
        })
        print("close!" + localtime + '--' + name)
        targetDev.status = 'close'
        targetDev.save()


def openSensor(name):
    from sensors.models import SystemSitting
    manualStatus = SystemSitting.objects.get(type_name='manual').status
    if not manualStatus:
        import time
        targetDev = DevInfo.objects.get(dev_name=name)
        localtime = time.asctime(time.localtime(time.time()))
        """开启传感器"""
        channel_layer = get_channel_layer()

        async_to_sync(channel_layer.group_send)("sensors", {
            "type": "events",
            "message": {
                'type': 'status',
                'msg': '已开启'
            }
        })
        print("open!" + localtime + '--' + name)
        targetDev.status = 'open'
        targetDev.save()
'''


# 屏蔽自动底层
def closeSensor(name):
    import time
    from sensors.bottomfac.bottom import tcp
    targetDev = DevInfo.objects.get(dev_name=name)
    localtime = time.asctime(time.localtime(time.time()))
    """关闭传感器"""
    channel_layer = get_channel_layer()
    if tcp.tcpSwitchClose(name):
        async_to_sync(channel_layer.group_send)("sensors", {
            "type": "events",
            "message": {
                'type': 'status',
                'msg': '已关闭'
            }
        })
        print("close!" + localtime + '--' + name)
        targetDev.status = 'close'
        targetDev.save()
    else:
        if tcp.tcpSwitchClose(name):
            async_to_sync(channel_layer.group_send)("sensors", {
                "type": "events",
                "message": {
                    'type': 'status',
                    'msg': '出现错误，未正常关闭设备'
                }
            })
            print("close err!" + localtime + '--' + name)
            targetDev.status = 'open'
            targetDev.save()


def openSensor(name):
    import time
    from sensors.bottomfac.bottom import tcp
    targetDev = DevInfo.objects.get(dev_name=name)
    localtime = time.asctime(time.localtime(time.time()))
    """开启传感器"""
    channel_layer = get_channel_layer()
    if tcp.tcpSwitchOpen(name):
        async_to_sync(channel_layer.group_send)("sensors", {
            "type": "events",
            "message": {
                'type': 'status',
                'msg': '已开启'
            }
        })
        print("open!" + localtime + '--' + name)
        targetDev.status = 'open'
        targetDev.save()
    else:
        async_to_sync(channel_layer.group_send)("sensors", {
            "type": "events",
            "message": {
                'type': 'status',
                'msg': '出现错误，未正常开启设备'
            }
        })
        print("open err!" + localtime + '--' + name)
        targetDev.status = 'close'
        targetDev.save()


def resetSensorState(name, times):
    from sensors.bottomfac.bottom import tcp
    targetDev = DevInfo.objects.get(dev_name=name)
    now = int(time.time())  # 当前时间戳
    now_date = datetime.datetime.now().strftime('%Y-%m-%d')  # 当日时间
    tmp_arr = []
    channel_layer = get_channel_layer()
    for i in times:
        startTime_arr = time.strptime(now_date + ' ' + i[0], "%Y-%m-%d %H:%M:%S")
        endTime_arr = time.strptime(now_date + ' ' + i[1], "%Y-%m-%d %H:%M:%S")
        startTime = int(time.mktime(startTime_arr))
        endTime = int(time.mktime(endTime_arr))
        if startTime <= now < endTime:
            tmp_arr.append(True)
        else:
            tmp_arr.append(False)
    if True in tmp_arr:
        # 打开设备
        if tcp.tcpSwitchOpen(name):
            targetDev.status = 'open'
            targetDev.save()
        else:
            async_to_sync(channel_layer.group_send)("sensors", {
                "type": "events",
                "message": {
                    'type': 'status',
                    'msg': '自动开启' + name + '失败'
                }
            })
    else:
        # 关闭设备
        if tcp.tcpSwitchClose(name):
            targetDev.status = 'close'
            targetDev.save()
        else:
            async_to_sync(channel_layer.group_send)("sensors", {
                "type": "events",
                "message": {
                    'type': 'status',
                    'msg': '自动关闭' + name + '失败'
                }
            })


def resetAllSensorsState():
    from sensors.bottomfac.bottom import tcp
    targetDev = DevInfo.objects.all()
    channel_layer = get_channel_layer()
    for i in targetDev:
        if i.type_name_en != 'squirm':
            if i.auto_times:
                newTimes = []
                new_item = i.auto_times.split(';')
                for j in new_item:
                    newTimes.append(j.split('-'))
                resetSensorState(i.dev_name, newTimes)
            else:
                if tcp.tcpSwitchClose(i.dev_name):
                    currentDev = DevInfo.objects.get(dev_name=i.dev_name)
                    currentDev.status = 'close'
                    currentDev.save()
                else:
                    async_to_sync(channel_layer.group_send)("sensors", {
                        "type": "events",
                        "message": {
                            'type': 'status',
                            'msg': '自动关闭' + i.dev_name + '失败'
                        }
                    })
        else:
            if tcp.tcpSwitchClose(i.dev_name):
                currentDev = DevInfo.objects.get(dev_name=i.dev_name)
                currentDev.status = 'close'
                currentDev.save()
                # 添加定时器

    print('设备状态校对')


# 打开关闭风扇
def toggleFan(i):
    from sensors.models import SystemSitting
    from sensors.bottomfac.bottom import tcp
    manualStatus = SystemSitting.objects.get(type_name='manual').status
    if not manualStatus:
        channel_layer = get_channel_layer()
        targetDev = DevInfo.objects.get(dev_name='排风扇')
        if i:
            # 打开风扇
            if tcp.tcpSwitchOpen('排风扇'):
                targetDev.status = 'open'
                targetDev.save()
                async_to_sync(channel_layer.group_send)("sensors", {
                    "type": "events",
                    "message": {
                        'type': 'status',
                        'msg': '超出设定值，已自动开启排风扇'
                    }
                })
            else:
                async_to_sync(channel_layer.group_send)("sensors", {
                    "type": "events",
                    "message": {
                        'type': 'status',
                        'msg': '超出设定值，自动开启排风扇失败'
                    }
                })

        else:
            # 关闭风扇
            if tcp.tcpSwitchClose('排风扇'):
                targetDev.status = 'close'
                targetDev.save()
                async_to_sync(channel_layer.group_send)("sensors", {
                    "type": "events",
                    "message": {
                        'type': 'status',
                        'msg': '排风扇自动关闭'
                    }
                })
            else:
                async_to_sync(channel_layer.group_send)("sensors", {
                    "type": "events",
                    "message": {
                        'type': 'status',
                        'msg': '排风扇自动关闭失败'
                    }
                })


# 范围超过风扇的阈值进行的函数
def setAutoForFan():
    # 获取数据库中风扇开启的时间设定
    targetDev = DevInfo.objects.get(dev_name='排风扇')
    if targetDev.status == 'open':  # 避免重复开启
        return
    interval = float(targetDev.auto_times)
    # 导入定时组件
    from sensors.common.Scheduler import scheduler
    # 删除风扇定时任务
    try:
        scheduler.remove_job('fan_close')
    except:
        pass
    finally:
        # 指定关闭的时间
        closeTime = (datetime.datetime.now() + datetime.timedelta(minutes=interval)).strftime("%Y-%m-%d %H:%M:%S")
        # 执行开启风扇
        toggleFan(True)
        # 添加风扇关闭任务
        scheduler.add_job(toggleFan, 'date', run_date=closeTime, args=[False], id="fan_close")

#open 蠕动泵
def openRu():
    from sensors.bottomfac.bottom import tcp
    channel_layer = get_channel_layer()
    targetDev = DevInfo.objects.get(dev_name='蠕动泵')
    if tcp.tcpSwitchOpen('蠕动泵'):
        targetDev.status = 'open'
        targetDev.save()
        async_to_sync(channel_layer.group_send)("sensors", {
            "type": "events",
            "message": {
                'type': 'status',
                'msg': '已自动开启蠕动泵'
            }
        })
    else:
        async_to_sync(channel_layer.group_send)("sensors", {
            "type": "events",
            "message": {
                'type': 'status',
                'msg': '自动开启蠕动泵失败'
            }
        })

# close 蠕动泵
def closeRu():
    from sensors.bottomfac.bottom import tcp
    channel_layer = get_channel_layer()
    targetDev = DevInfo.objects.get(dev_name='蠕动泵')
    # 关闭泵
    from sensors.common.Scheduler import scheduler
    if tcp.tcpSwitchClose('蠕动泵'):
        targetDev.status = 'close'
        targetDev.save()
        async_to_sync(channel_layer.group_send)("sensors", {
            "type": "events",
            "message": {
                'type': 'status',
                'msg': '已自动关闭蠕动泵'
            }
        })
        try:
            scheduler.remove_job('ru_open')
            scheduler.remove_job('ru_close')
        except:
            pass
    else:
        async_to_sync(channel_layer.group_send)("sensors", {
            "type": "events",
            "message": {
                'type': 'status',
                'msg': '自动关闭蠕动泵失败'
            }
        })

def openru():
    from channels.layers import get_channel_layer
    from asgiref.sync import async_to_sync
    from sensors.models import DevInfo
    from sensors.bottomfac.bottom import tcp
    # from threading import Timers
    channel_layer = get_channel_layer()
    targetDev = DevInfo.objects.get(dev_name='蠕动泵')
    if tcp.tcpSwitchOpen('蠕动泵'):
        targetDev.status = 'open'
        targetDev.save()
        async_to_sync(channel_layer.group_send)("sensors", {
            "type": "events",
            "message": {
                'type': 'status',
                'msg': '已自动开启蠕动泵'
            }
        })
    else:
        async_to_sync(channel_layer.group_send)("sensors", {
            "type": "events",
            "message": {
                'type': 'status',
                'msg': '自动开启蠕动泵失败'
            }
        })
def closeru():
    from channels.layers import get_channel_layer
    from asgiref.sync import async_to_sync
    from sensors.models import DevInfo
    from sensors.bottomfac.bottom import tcp
    # from threading import Timers
    channel_layer = get_channel_layer()
    targetDev = DevInfo.objects.get(dev_name='蠕动泵')
    if tcp.tcpSwitchClose('蠕动泵'):
        targetDev.status = 'close'
        targetDev.save()
        async_to_sync(channel_layer.group_send)("sensors", {
            "type": "events",
            "message": {
                'type': 'status',
                'msg': '已自动关闭蠕动泵'
            }
        })
    else:
        async_to_sync(channel_layer.group_send)("sensors", {
            "type": "events",
            "message": {
                'type': 'status',
                'msg': '自动关闭蠕动泵失败'
            }
        })
# 范围超出设定值后开启蠕动泵
def setAutoForSquirm():
    # 获取手动自动状态
    from sensors.models import SystemSitting
    from sensors.common.Scheduler import scheduler
    # 获取数据库中开启的时间设定
    targetDev = DevInfo.objects.get(dev_name='蠕动泵')
    interval = float(targetDev.auto_times)
    logging.info(datetime.datetime.now(),'----------')
    # 添加蠕动泵打开任务
    scheduler.add_job(openRu,
                      'date',
                      id='ru_open',
                      next_run_time=datetime.datetime.now())
    # 添加蠕动泵关闭任务
    startTime = (datetime.datetime.now() + datetime.timedelta(minutes=interval)).strftime("%Y-%m-%d %H:%M:%S")
    scheduler.add_job(closeRu,
                      'date',
                      id='ru_close',
                      next_run_time=startTime)


# 回到范围内停止蠕动泵的定时
def closeAutoForSquirm():
    from sensors.models import SystemSitting
    from sensors.bottomfac.bottom import tcp
    from sensors.common.Scheduler import scheduler
    channel_layer = get_channel_layer()
    targetDev = DevInfo.objects.get(dev_name='蠕动泵')
    try:
        scheduler.remove_job('ru_open')
        scheduler.remove_job('ru_close')
    except:
        pass
    # 执行关闭
    if tcp.tcpSwitchClose('蠕动泵'):
        targetDev.status = 'close'
        targetDev.save()
        async_to_sync(channel_layer.group_send)("sensors", {
            "type": "events",
            "message": {
                'type': 'status',
                'msg': '已自动关闭蠕动泵'
            }
        })
    else:
        async_to_sync(channel_layer.group_send)("sensors", {
            "type": "events",
            "message": {
                'type': 'status',
                'msg': '自动关闭蠕动泵失败'
            }
        })
